package logic

import (
	"context"
	"encoding/json"
	"strconv"
	"time"
	"work/model/cache"
	"work/model/mysql"

	"work/workrpc/internal/svc"
	"work/workrpc/workrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type ContentShowLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewContentShowLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ContentShowLogic {
	return &ContentShowLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ContentShowLogic) ContentShow(in *workrpc.ContentShowRequest) (*workrpc.ContentShowResponse, error) {
	// todo: add your logic here and delete this line
	var list []*workrpc.UserAndContent
	var story mysql.Story
	result, _ := cache.Rdb.Get(l.ctx, "key"+strconv.FormatInt(in.StoryId, 10)).Result()
	if result == "" {
		var err error
		list, err = mysql.UserAndContent(mysql.DB, in)
		if err != nil {
			return nil, err
		}
		err = story.FindStory(mysql.DB, in.StoryId)
		if err != nil {
			return nil, err
		}

		marshal, _ := json.Marshal(list)

		cache.Rdb.Set(l.ctx, "key"+strconv.FormatInt(in.StoryId, 10), marshal, time.Minute*15)
	} else {
		json.Unmarshal([]byte(result), &list)
	}

	return &workrpc.ContentShowResponse{
		Title: story.Title,
		List:  list,
	}, nil
}
